/**
 * 
 */
package info.sswap.ontologies.modularity.repo.rdf;

import info.sswap.ontologies.modularity.Module;
import info.sswap.ontologies.modularity.ModuleExtractor;
import info.sswap.ontologies.modularity.owlapi.OWLAPIModule;
import info.sswap.ontologies.modularity.repo.OntologyRepositoryException;
import info.sswap.ontologies.modularity.repo.RepositoryEntry;

import java.net.URI;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;

import uk.ac.manchester.cs.owlapi.modularity.ModuleType;
import edu.arizona.bio5.onto.decomposition.Atom;
import edu.arizona.bio5.onto.decomposition.AtomicDecomposition;
import edu.arizona.bio5.onto.decomposition.persistent.PersistentAtomicDecomposition;

/**
 * @author Pavel Klinov
 *
 */
public class RDFADEntry implements RepositoryEntry {

	private final PersistentAtomicDecomposition mAD;

	public RDFADEntry(PersistentAtomicDecomposition ad) {
		mAD = ad;
	}
	
	@Override
	public URI getURI() {
		return mAD.getOntologyURI();
	}

	public Collection<URI> getRelatedTerms(URI term) {
		AtomicDecomposition ad = (AtomicDecomposition) mAD;
		Collection<URI> sig = new HashSet<URI>();
		
		for (Atom atom : ad.getAtomsForTerm(term)) {
			for (OWLEntity entity : atom.getSignature()) {
				sig.add(entity.getIRI().toURI());
			}
		}
		
		return sig;
	}
	
	public Module getAxiomsForTerm(URI term) throws OntologyRepositoryException {
		AtomicDecomposition ad = (AtomicDecomposition) mAD;
		Set<OWLAxiom> axioms = new HashSet<OWLAxiom>();
		
		for (Atom atom : ad.getAtomsForTerm(term)) {
			axioms.addAll(atom.getAllAxioms());
		}
		
		try {
			return new OWLAPIModule(OWLManager.createOWLOntologyManager().createOntology(axioms));
		} catch (OWLOntologyCreationException e) {
			throw new OntologyRepositoryException(e);
		}
	}

	@Override
	public ModuleExtractor getModuleExtractor(ModuleType modType) throws OntologyRepositoryException {
		if (!modType.equals(mAD.getModuleType())) {
			throw new OntologyRepositoryException("Unsupported module type");
		}
		else {
			return new ADModuleExtractor(mAD);
		}
	}

	@Override
	public void close() {
		mAD.close();
	}
}